package templates

import (
	"fmt"
	"sigs.k8s.io/yaml"
	"strings"
	"text/template"
)

var GomplateFuncs = template.FuncMap{
	"fromYaml": FromYAML,
	"toYaml":   ToYAML,
	"indent":   Indent,
	"nindent":  Nindent,
}

// FromYAML decodes a YAML string into an interface{}. This allows injection templates to access
// configs defined as YAML strings.
func FromYAML(in string) (interface{}, error) {
	var out interface{}

	if err := yaml.Unmarshal([]byte(in), &out); err != nil {
		return nil, fmt.Errorf("failed to unmarshal yaml with error: %v. source: %q", err, in)
	}
	return out, nil
}

// ToYAML encodes an interface{} into a YAML string.
func ToYAML(in interface{}) (string, error) {
	out, err := yaml.Marshal(in)
	if err != nil {
		return "", fmt.Errorf("failed to unmarshal yaml with error: %v. source: %q", err, out)
	}
	if in == nil {
		out = []byte{}
	}

	return string(out), nil
}

func Indent(in string, spacesNum int) string {
	spaces := strings.Repeat(" ", spacesNum)
	out := strings.Replace(in, "\n", "\n"+spaces, -1)
	return out + "\n"
}

func Nindent(in string, spacesNum int) string {
	out := "\n" + in
	return Indent(out, spacesNum)
}
